<?php

declare(strict_types=1);

namespace App\Third\Task;

use App\Resource\Service\BuildGoodsService;
use App\Third\Model\ShopSchemeGoodsPriceModel;
use App\Third\Model\ShopSchemeModel;
use App\Third\Service\Lsy\LsyMainGoodsService;
use Hyperf\Crontab\Annotation\Crontab;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\Parallel;
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;

/**
 * @Crontab(name="LsyShopGoodsPriceTask", rule="30 6 * * *", callback="task", memo="每天6.30点拉取销售方案对应价格")
 * Class LsyShopGoodsPriceTask
 * @package App\Third\Task
 */
class LsyShopGoodsPriceTask
{
    /**
     * @Inject
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var LoggerInterface
     */
    protected $logger;

    public function __construct(LoggerFactory $loggerFactory)
    {
        $this->logger = $loggerFactory->get('拉取方案价格', 'crmScheme');
    }

    public function task()
    {
        if (env('APP_ENV') != 'dev') {
            $resMsg = '根据方案ID获取商品详情执行完成-';
            $s = (int)(microtime(true) * 1000);
            $schemeArr = ShopSchemeModel::query()->where(['is_enable' => 1])->pluck('schemeID');
            $container = $this->container;
            $crmGoodsService = $container->get(LsyMainGoodsService::class);
            $spm = $container->get(ShopSchemeGoodsPriceModel::class);
            $connection = $spm->getConnectionName();
            $table = $spm->getTable();
            $columns = '`schemeID`,`crm_goods_id`,`name`,`stdPrice`,`price`,`create_date`';
            $db = Db::connection($connection)->getPdo();
            $parallel = new Parallel(15);
            $crmGoodsData = [];
            foreach ($schemeArr as $sid) {
                $parallel->add(function () use (&$crmGoodsData, $crmGoodsService, $sid) {
                    $menuInfoArr = $crmGoodsService->singlePullShopInfoMenu($sid);
                    $date = date('Y-m-d');
                    foreach ($menuInfoArr['thirdPriLocalItemListVo']['itemList'] as $value) {
                        $crmGoodsData[] = "({$sid},'{$value['id']}','{$value['name']}',{$value['stdPrice']},{$value['price']},'{$date}')";
                    }
                    return true;
                });
            }
            try {
                $parallel->wait();
                $db->exec("truncate `{$table}`");
                $parameters = implode(',', $crmGoodsData);
                $sql = "insert into {$table} ({$columns}) values {$parameters}";
                $db->exec($sql);//不记录sql
                $resMsg .= '-消耗时间' . (microtime(true) * 1000 - $s) . 'ms';
                $this->logger->info('更新价格执行完成', ['update success' => $resMsg]);
            } catch (\Exception $e) {
                $this->logger->error('更新价格异常', ['error' => $e->getMessage()]);
            }
            $container->get(BuildGoodsService::class)->buildAllShopTimelyGoodsListToRedis(null);//构建商品资料
        }
    }

}
